/**
 * 请求工具类
 * @author liu_jshan
 * @version 1.2 20240330
 */
import consoleUtil from "./consoleUtil"

export async function get(url, opinions) {
  const headers = opinions ? opinions.headers : {}
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers: {
          token: localStorage.getItem('token'),
          ...headers,
        }
      }
    )
    const responseJson = await response.json()
    responseIntercept(responseJson)
    return responseJson
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}

export async function post(url, opinions, otherSupport) {
  const headers = {
    'Content-Type': 'application/json;charset=utf-8',
    token: localStorage.getItem('token'),
    ...(opinions ? opinions.headers : null)
  }
  if (otherSupport && otherSupport.notSetContentType) {
    delete headers['Content-Type']
  }
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers,
        method: 'POST'
      }
    )
    const responseJson = await response.json()
    responseIntercept(responseJson)
    return responseJson
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}

export async function _delete(url, opinions) {
  const headers = opinions ? opinions.headers : {}
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          token: localStorage.getItem('token'),
          ...headers,
        },
        method: 'DELETE'
      }
    )
    const responseJson = await response.json()
    responseIntercept(responseJson)
    return responseJson
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}

export async function put(url, opinions) {
  const headers = opinions ? opinions.headers : {}
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          token: localStorage.getItem('token'),
          ...headers,
        },
        method: 'PUT'
      }
    )
    const responseJson = await response.json()
    responseIntercept(responseJson)
    return responseJson
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}

/**
 * get请求带参数
 * @param {请求地址} url 
 * @param {请求参数} params object
 */
export async function getWithParams(url, params, opinions) {
  if (params) {
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&')
    } else {
      url += '&' + paramsArray.join('&')
    }
  }
  return await get(url, opinions)
}


export async function getText(url, opinions) {
  const headers = opinions ? opinions.headers : {}
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers: {
          ...headers,
          token: localStorage.getItem('token')
        }
      }
    )
    return await response.text()
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}


export async function getBlob(url, opinions) {
  const headers = opinions ? opinions.headers : {}
  let response = null
  try {
    response = await fetch(url,
      {
        ...opinions,
        headers: {
          ...headers,
          token: localStorage.getItem('token')
        }
      }
    )
    return await response.blob()
  } catch (error) {
    responseIntercept(response)
    consoleUtil.log('Request Failed', error)
  }
}

/**
 * 响应拦截器
 * @param {*} response 
 */
function responseIntercept(response) {
  if (response && response.code) {
    switch (response.code + '') {
      case '401':
        // window.location.href = '/login'
        window.dispatchEvent(new CustomEvent('navigateTo', { detail: { path: '/login' } }))
        break
      default:
        break
    }
  } else if (response && response.status) {
    switch (response.status + '') {
      case '404':
        // window.location.href = '/404'
        window.dispatchEvent(new CustomEvent('navigateTo', { detail: { path: '/404' } }))
        break
      case '500':
        // window.location.href = '/500'
        window.dispatchEvent(new CustomEvent('navigateTo', { detail: { path: '/500' } }))
        break
      case '403':
        // window.location.href = '/403'
        window.dispatchEvent(new CustomEvent('navigateTo', { detail: { path: '/403' } }))
        break
      default:
        break
    }
  }
}